package objects;
import gui.MainFrame;
import gui.MainPanel;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


public class Drawer {
	volatile static boolean canDraw = true;
    private static volatile Drawer instance = null;
    private BufferedImage img;
    private static String DS;
    private String filenameOutputFile = "";
	static int it =0;
    private File output;
	private Drawer () {
		this.DS = Test.getDS();
		filenameOutputFile = "."+DS+"images"+DS+"tmp" +DS + "output.png";
		this.output = new File(filenameOutputFile);
	}
	
    public static Drawer getInstance() {
        if (instance == null) {
            synchronized (Drawer.class) {
                if (instance == null) {
                    instance = new Drawer();
                }
            }
        }
        return instance;
    }
    
    public BufferedImage getImage(){
    	return img;
    }
    
    public void init(BufferedImage img) {
    	this.img = img;
    }

    public synchronized void drawImage(MyShape ms) {
        while (canDraw == false) 
        {
             try { wait(); }
             catch (InterruptedException e) { } 
             finally { } 
        } 

		for(int i = 0; i<ms.getSize(); i++){
		Point p = ms.getPoint(i);
			
			img.setRGB(p.getX(), p.getY(), Color.RED.getRGB());
			
			img.setRGB(p.getX()+1, p.getY()+1, Color.RED.getRGB());
			img.setRGB(p.getX(), p.getY()+1, Color.RED.getRGB());
			img.setRGB(p.getX()+1, p.getY(), Color.RED.getRGB());
			img.setRGB(p.getX()-1, p.getY()-1, Color.RED.getRGB());
			img.setRGB(p.getX(), p.getY()-1, Color.RED.getRGB());
			img.setRGB(p.getX()-1, p.getY(), Color.RED.getRGB());
		}
		System.out.println("*");

		MainFrame.refreshImage();
		try {
			javax.imageio.ImageIO.write(img, "png", output);
			
			System.out.println("Zapisalem " + filenameOutputFile); 
		} catch (IOException e) {
			e.printStackTrace();
		}
		
        canDraw = true;
        
        notify(); 
   }
}
